﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DTO;
using BUS;

namespace QuanLyNhaSach.Book
{
    public partial class FrmBookListSearch : DevComponents.DotNetBar.Office2007Form
    {
        BindingList<BookDTO> _listBook;
        BindingList<BookDTO> _listBookSearch;
        bool _isSearching;
        BookBUS _bookBUS;
        RuleObjectBUS RuleBUS;
        int rowIndex = -1;

        public FrmBookListSearch()
        {
            InitializeComponent();
            _listBook = new BindingList<BookDTO>();
            _listBookSearch = new BindingList<BookDTO>();
            _bookBUS = new BookBUS();
            RuleBUS = new RuleObjectBUS();
            dtgBookList.AutoGenerateColumns = false;
            _isSearching = false;
            dbiTo.DisplayFormat = "N0";
            dbiFrom.DisplayFormat = "N0";
            dbiFrom.Value = 0;
            dbiTo.Value = 20000;
        }

        private void FrmBookList_Load(object sender, EventArgs e)
        {
            this.VisibleChanged += new EventHandler(FrmBookList_VisibleChanged);
            CheckPermission();
        }

        private void CheckPermission()
        {
            btnDelete.Enabled = RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionAuthor);
            btnUpdate.Enabled = btnDelete.Enabled;
        }

        void FrmBookList_VisibleChanged(object sender, EventArgs e)
        {
            LoadListBook();
        }

        private void LoadListBook()
        {
            _listBook = _bookBUS.GetNewBindingList();
            dtgBookList.DataSource = _listBook;
            GenerateGridColumn();
        }

        private void ClearForm()
        {
            txtAuthor.Clear();
            txtBookCode.Clear();
            txtBookName.Clear();
            txtCategory.Clear();
            txtBookCode.Focus();
            _isSearching = false;
        }

        private void GenerateGridColumn()
        {
            Global.GenerateDeleteColumn(dtgBookList, colDel.Index);
            Global.GenerateEditColumn(dtgBookList, colEdit.Index);
            Global.GenerateNumber(dtgBookList, colNumber.Index);
        }

        private BindingList<BookDTO> GetBindingList(List<BookDTO> list)
        {
            BindingList<BookDTO> bingdingList = new BindingList<BookDTO>();
            foreach (BookDTO book in list)
            {
                bingdingList.Add(book);
            }

            return bingdingList;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            _listBookSearch = GetBindingList( _listBook.Where(b => b.BookCode.Contains(txtBookCode.Text) &&
                b.BookName.ToUpper().Contains(txtBookName.Text.ToUpper()) &&
                b.BookCost > dbiFrom.Value && b.BookCost < dbiTo.Value &&
                b.CategoryName.ToUpper().Contains(txtCategory.Text.ToUpper()) &&
                b.AuthorName.ToUpper().Contains(txtAuthor.Text.ToUpper())).ToList());

            dtgBookList.DataSource = _listBookSearch;
            GenerateGridColumn();
            _isSearching = true;
        }

        private void btnViewAll_Click(object sender, EventArgs e)
        {
            LoadListBook();
            ClearForm();
        }

        public void BookListChangeAfterInsert(int id)
        {
            BookDTO bookDto = _bookBUS.GetBookByID(id);
            _listBook.Add(bookDto);

            rowIndex = dtgBookList.Rows.GetLastRow(DataGridViewElementStates.None);
            dtgBookList[colEdit.Index, rowIndex].Value = Properties.Resources.edit_16;
            dtgBookList[colDel.Index, rowIndex].Value = Properties.Resources.deletered;
            if (rowIndex == 0)
            {
                dtgBookList[colNumber.Index, rowIndex].Value = 1;
            }
            else
            {
                dtgBookList[colNumber.Index, rowIndex].Value = int.Parse(dtgBookList[colNumber.Index, rowIndex - 1].Value.ToString()) + 1;
            }
        }

        public void BookChangeAfterUpdate(int id)
        {
            BookDTO bookDto = _bookBUS.GetBookByID(id);

            dtgBookList[colBookName.Index, rowIndex].Value = bookDto.BookName;
            dtgBookList[colAuthor.Index, rowIndex].Value = bookDto.AuthorName;
            dtgBookList[colCategory.Index, rowIndex].Value = bookDto.CategoryName;
            dtgBookList[colCost.Index, rowIndex].Value = bookDto.BookCost;
        }

        private void dtgBookList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                if (e.ColumnIndex == colEdit.Index)
                {
                    rowIndex = e.RowIndex;
                    UpdateBook();
                }
                else if (e.ColumnIndex == colDel.Index)
                {
                    DeleteBook();
                }
            }
        }

        private void DeleteBook()
        {
            if (dtgBookList.Rows.Count > 0)
            {
                if (!RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionBook))
                {
                    Global.SetMessage(lblMessage, "Bạn không có quyền thực hiện thao tác này!", false);
                    return;
                }

                if (Global.ShowMessageBoxDelete("Bạn chắc chắn muốn xóa sách này ?") == DialogResult.Yes)
                {
                    int success = 0, faile = 0;
                    foreach (DataGridViewRow row in dtgBookList.SelectedRows)
                    {
                        int bookID = int.Parse(row.Cells[colBookID.Index].Value.ToString());
                        if (_bookBUS.DeleteBook(bookID))
                        {
                            if (_isSearching)
                            {
                                _listBookSearch.Remove(_listBookSearch.First(c => c.BookID == bookID));
                            }
                            else
                            {
                                _listBook.Remove(_listBook.First(c => c.BookID == bookID));
                            }
                            success++;
                        }
                        else
                        {
                            faile++;
                        }
                    }

                    Global.SetMessage(lblMessage, string.Format("Xóa thành công : {0} dòng, thất bại : {1} dòng.", success, faile), true);
                    Global.GenerateNumber(dtgBookList, colNumber.Index);
                }
            }
        }

        private void UpdateBook()
        {
            if (!RuleBUS.CheckPermission(Global.GroupID, (int)RuleObject.ActionBook))
            {
                Global.SetMessage(lblMessage, "Bạn không có quyền thực hiện thao tác này!", false);
                return;
            }

            int id = int.Parse(dtgBookList[colBookID.Index,rowIndex].Value.ToString());
            Book.FrmBookDetail frm = new FrmBookDetail { Action = ActionName.Update, _bookID = id };
            frm.ShowDialog();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (dtgBookList.Rows.Count > 0)
            {
                rowIndex = dtgBookList.CurrentRow.Index;
                UpdateBook();
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            DeleteBook();
        }
    }
}
